using System;
using System.Globalization;
using System.ServiceModel;


namespace ZPod.MTG.Communication.Web
{
	public class ServiceClient<TChannel> : ClientBase<TChannel> where TChannel : class
	{
		#region Constructors

		public ServiceClient( ) : base( ) { }

		public ServiceClient( string endpointConfigurationName ) : base( endpointConfigurationName ) { }

		public ServiceClient( string endpointConfigurationName, string remoteAddress ) : base( endpointConfigurationName, new EndpointAddress( remoteAddress ) ) { }

		#endregion

		#region Properties

		public TChannel InvokerChannel
		{
			get
			{
				return base.Channel;
			}
		}

		#endregion

		#region Public Methods

		[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes" )]
		public static TChannel CreateServiceChannel( string endpointConfigurationName )
		{
			if ( endpointConfigurationName == null )
				throw new Exception( String.Format( CultureInfo.InvariantCulture, "El endpoint no existe", typeof( TChannel ).FullName ) );

			ChannelFactory<TChannel> factory = new ChannelFactory<TChannel>( endpointConfigurationName );

			return factory.CreateChannel( );
		}

		[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes" )]
		public static TChannel CreateServiceChannel( string endpointConfigurationName, string remoteAddress )
		{
			ChannelFactory<TChannel> factory = new ChannelFactory<TChannel>( endpointConfigurationName, new EndpointAddress( remoteAddress ) );
			return factory.CreateChannel( );
		}

		[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1000:DoNotDeclareStaticMembersOnGenericTypes")]
		public static void DisposeProxy( TChannel proxy )
		{
			ICommunicationObject wcfProxy = proxy as ICommunicationObject;
			if ( wcfProxy != null && wcfProxy.State == CommunicationState.Faulted )
			{
				wcfProxy.Abort( );
			}
			else if ( wcfProxy != null && wcfProxy.State != CommunicationState.Closed )
			{
				wcfProxy.Close( );
			}

			IDisposable dispProxy = proxy as IDisposable;
			if ( dispProxy != null )
				dispProxy.Dispose( );
		}
	
		#endregion
	}
}